package com.example.heimashop.view.activity;

import android.content.Intent;
import android.view.View;

import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.example.heimashop.base.BaseActivity;
import com.example.heimashop.database.AddressDao;
import com.example.heimashop.database.CartDao;
import com.example.heimashop.database.OrderDao;
import com.example.heimashop.databinding.ActivityOrderConfirmBinding;
import com.example.heimashop.model.Address;
import com.example.heimashop.model.CartItem;
import com.example.heimashop.model.Order;
import com.example.heimashop.utils.ToastUtils;
import com.example.heimashop.view.adapter.OrderGoodsAdapter;

import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

/**
 * 订单确认页面
 */
public class OrderConfirmActivity extends BaseActivity<ActivityOrderConfirmBinding> {

    private OrderGoodsAdapter adapter;
    private AddressDao addressDao;
    private CartDao cartDao;
    private OrderDao orderDao;
    private Address currentAddress;
    private List<CartItem> orderGoods = new ArrayList<>();
    private double totalPrice = 0;
    private ActivityResultLauncher<Intent> addressLauncher;

    @Override
    protected ActivityOrderConfirmBinding getViewBinding() {
        return ActivityOrderConfirmBinding.inflate(getLayoutInflater());
    }

    @Override
    protected void initView() {
        // 设置标题栏返回按钮
        binding.toolbar.setNavigationOnClickListener(v -> finish());

        // 初始化RecyclerView
        binding.rvGoods.setLayoutManager(new LinearLayoutManager(this));
        adapter = new OrderGoodsAdapter();
        binding.rvGoods.setAdapter(adapter);

        // 初始化数据库
        addressDao = new AddressDao(this);
        cartDao = new CartDao(this);
        orderDao = new OrderDao(this);

        // 注册地址选择Activity Result
        addressLauncher = registerForActivityResult(
                new ActivityResultContracts.StartActivityForResult(),
                result -> {
                    if (result.getResultCode() == RESULT_OK && result.getData() != null) {
                        // 获取选中的地址ID
                        int addressId = result.getData().getIntExtra("address_id", -1);
                        if (addressId != -1) {
                            // 加载选中的地址
                            currentAddress = addressDao.getAddressById(addressId);
                            updateAddressDisplay();
                        }
                    }
                }
        );
    }

    @Override
    protected void initData() {
        // 获取购物车中选中的商品
        loadOrderGoods();

        // 加载地址
        loadAddress();

        // 计算总价
        calculateTotalPrice();
    }

    @Override
    protected void initListener() {
        // 更改地址
        binding.tvChangeAddress.setOnClickListener(v -> {
            Intent intent = new Intent(this, AddressListActivity.class);
            intent.putExtra("select_mode", true); // 设置为选择模式
            addressLauncher.launch(intent);
        });

        // 提交订单
        binding.btnSubmit.setOnClickListener(v -> submitOrder());
    }

    /**
     * 加载订单商品
     */
    private void loadOrderGoods() {
        List<CartItem> allItems = cartDao.getAllCartItems();
        orderGoods.clear();
        for (CartItem item : allItems) {
            if (item.isChecked()) {
                orderGoods.add(item);
            }
        }
        adapter.setData(orderGoods);
    }

    /**
     * 加载地址（首次加载默认地址）
     */
    private void loadAddress() {
        currentAddress = addressDao.getDefaultAddress();
        updateAddressDisplay();
    }

    /**
     * 更新地址显示
     */
    private void updateAddressDisplay() {
        if (currentAddress != null) {
            // 显示地址信息
            binding.llAddressInfo.setVisibility(View.VISIBLE);
            binding.tvNoAddress.setVisibility(View.GONE);

            binding.tvConsignee.setText(currentAddress.getConsignee());
            binding.tvPhone.setText(currentAddress.getPhone());
            binding.tvAddress.setText(currentAddress.getFullAddress());
        } else {
            // 显示无地址提示
            binding.llAddressInfo.setVisibility(View.GONE);
            binding.tvNoAddress.setVisibility(View.VISIBLE);
        }
    }

    /**
     * 计算总价
     */
    private void calculateTotalPrice() {
        totalPrice = 0;
        for (CartItem item : orderGoods) {
            totalPrice += item.getGoodsPrice() * item.getGoodsCount();
        }

        // 显示价格
        String priceStr = String.format(Locale.CHINA, "¥%.2f", totalPrice);
        binding.tvGoodsPrice.setText(priceStr);
        binding.tvTotalPrice.setText(priceStr);
    }

    /**
     * 提交订单
     */
    private void submitOrder() {
        // 检查地址
        if (currentAddress == null) {
            ToastUtils.showShort(this, "请先选择收货地址");
            return;
        }

        // 检查商品
        if (orderGoods.isEmpty()) {
            ToastUtils.showShort(this, "没有可提交的商品");
            return;
        }

        // 禁用提交按钮，防止重复提交
        binding.btnSubmit.setEnabled(false);

        // 创建订单对象
        Order order = new Order();
        order.setOrderNo(OrderDao.generateOrderNo());
        order.setConsignee(currentAddress.getConsignee());
        order.setPhone(currentAddress.getPhone());
        order.setAddress(currentAddress.getFullAddress());
        order.setTotalPrice(totalPrice);
        order.setStatus("wait_pay"); // 待支付
        order.setCreateTime(System.currentTimeMillis());

        // 保存订单到数据库
        long orderId = orderDao.createOrder(order, orderGoods);

        if (orderId != -1) {
            // 订单创建成功，删除购物车中已选中的商品
            cartDao.deleteCheckedItems();

            ToastUtils.showShort(this, "订单提交成功");

            // 立即返回，不等待任何操作
            setResult(RESULT_OK);
            finish();
        } else {
            ToastUtils.showShort(this, "订单提交失败");
            // 重新启用提交按钮
            binding.btnSubmit.setEnabled(true);
        }
    }
}
